//
//  HJChatGroupManager.m
//  KaiChat
//
//  Created by lx on 2023/10/23.
//

#import "HJChatGroupManager.h"
#import "HJChatGroupModel.h"
#import "HJGroupMemberModel.h"

@implementation HJChatGroupManager

- (void)queryGroupInfoByGroupId:(NSString *)groupId completion:(void (^)(HJChatGroupModel * _Nullable groupModel))completion {
    HJChatGroupModel *groupModel = [self queryGroupInfoByGroupId:groupId];
    if (groupModel) {
        completion(groupModel);
    } else {
        [self loadGroupInfoByGroupId:groupId completion:completion];
    }
}

- (HJChatGroupModel *)queryGroupInfoByGroupId:(NSString *)groupId {
    NSString *where = [NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"groupId"),bg_sqlValue(groupId)];
    return [HJChatGroupModel bg_find:[HJChatGroupModel bg_tableName] where:where].lastObject;
}

- (void)createGroupByGroupIdWithUserIds:(NSArray *)userIds completion:(void (^)(HJChatGroupModel * _Nullable groupModel))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_createGroup parameters:@{
        @"user_ids": userIds,
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        HJChatGroupModel *groupModel = [HJChatGroupModel modelWithBlock:^(HJChatGroupModel * _Nonnull model) {
            model.role = @1;
            model.name = data[@"name"];
            model.memberNums = data[@"nums"];
            model.avatar = data[@"avatar"];
            model.groupId = toString(data[@"room_id"]);
        }];
        [groupModel bg_saveOrUpdateAsync:nil];
        !completion ?: completion(groupModel);
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(nil);
    }];
}

- (void)loadGroupInfoByGroupId:(NSString *)groupId completion:(void (^)(HJChatGroupModel * _Nullable groupModel))completion {
    [HJNetworking.shareNetwork POSTBodyJSON:API_groupInfo parameters:@{
        @"room_id": @(groupId.integerValue),
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        HJChatGroupModel *model = [HJChatGroupModel groupModelWithDict:data];
        [model bg_saveOrUpdateAsync:^(BOOL isSuccess) {
            dispatch_async_main_queue(^{
                !completion ?: completion(model);
            });
        }];
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(nil);
    }];
    
}

- (void)loadGroupListWithCompletion:(void (^)(NSArray <NSArray <HJChatGroupModel *>*>* _Nullable datas))completion {
  
    [HJNetworking.shareNetwork POSTBodyJSON:API_groupList parameters:nil success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
                
        NSArray *create_room = data[@"create_room"];
        NSArray *join_room = data[@"join_room"];
        
        NSMutableArray *datas = [NSMutableArray array];
        if ([create_room isKindOfClass:NSArray.class]) {
            [datas addObjectsFromArray:create_room];
        }
        if ([join_room isKindOfClass:NSArray.class]) {
            [datas addObjectsFromArray:join_room];
        }
        
        NSMutableArray *createDatas = [NSMutableArray array];
        NSMutableArray *joinDatas = [NSMutableArray array];
        NSMutableArray *allDatas = [NSMutableArray array];
        NSMutableArray *groupIds = [NSMutableArray array];

        for (NSDictionary *dict in datas) {
            [HJChatGroupModel modelWithBlock:^(HJChatGroupModel * _Nonnull model) {
                model.role = dict[@"role"];
                model.groupId = toString(dict[@"room_id"]);
                model.memberNums = dict[@"nums"];
                model.avatar = dict[@"avatar"];
                model.name = dict[@"name"];
                model.intro = dict[@"intro"];
                if ([model.role intValue] == 1) {//群主
                    [createDatas addObject:model];
                } else {
                    [joinDatas addObject:model];
                }
                [groupIds addObject:model.groupId];
            }];
        }
        
        [allDatas addObjectsFromArray:createDatas];
        [allDatas addObjectsFromArray:joinDatas];
        
        [HJChatGroupModel bg_saveOrUpdateArrayAsync:allDatas complete:^(BOOL isSuccess) {
            dispatch_async_main_queue(^{
                !completion ?: completion(@[createDatas, joinDatas]);
            });
            
            NSArray *models = [HJChatGroupModel bg_findAll:[HJChatGroupModel bg_tableName]];
            [models enumerateObjectsUsingBlock:^(HJChatGroupModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (![groupIds containsObject:obj.groupId]) {
                    [HJChatGroupModel bg_delete:[HJChatGroupModel bg_tableName] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"groupId"),bg_sqlValue(obj.groupId)]];
                }
            }];
        }];
    
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(nil);
    }];
    
}

- (void)openGroupInviteVerifyWithGroupId:(NSString *)groupId open:(BOOL)open completion:(void (^)(NSError * _Nullable error))completion {
    
    
}

- (void)exitGroupWithGroupId:(NSString *)groupId  completion:(void (^)(NSError * _Nullable error))completion {
    
}

- (void)disbandGroupWithGroupId:(NSString *)groupId  completion:(void (^)(NSError * _Nullable error))completion {
    
}


- (void)queryGroupMemberListWithGroupId:(NSString *)groupId completion:(void (^)(NSArray <HJGroupMemberModel *>* _Nullable datas))completion {
    [HJGroupMemberModel bg_findAsync:[HJGroupMemberModel bg_tableNameWithGroupId:groupId] where:nil complete:^(NSArray * _Nullable array) {
        !completion ?: completion(array);
    }];
}

- (NSArray *)queryGroupMemberListWithGroupId:(NSString *)groupId {
    return [HJGroupMemberModel bg_find:[HJGroupMemberModel bg_tableNameWithGroupId:groupId] where:nil];
}
 
- (void)loadGroupMemberListWithGroupId:(NSString *)groupId completion:(void (^)(NSArray <HJGroupMemberModel *>* _Nullable datas))completion {
    [HJNetworking.shareNetwork GET:API_groupMemberList parameters:@{
        @"room_id": @(groupId.integerValue),
        @"type": @2
    } success:^(NSDictionary * _Nonnull responseObject, NSArray *  _Nonnull data) {
        
        NSMutableArray *datas = [NSMutableArray arrayWithCapacity:data.count];
        for (NSDictionary *dict in data) {
            HJGroupMemberModel *model = [HJGroupMemberModel modelWithDict:dict];
            model.groupId = groupId;
            [datas addObject:model];
        }
        !completion ?: completion(datas);
        [HJGroupMemberModel bg_saveOrUpdateArrayAsync:datas complete:nil];
    } failure:^(NSError * _Nonnull error) {
        !completion ?: completion(nil);
    }];
    
}


@end
